package org.mat.ipaas.ucenter.service.modules.system.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.mat.framework.lang.dto.MatApiResponse;
import org.mat.ipaas.ucenter.biz.common.constant.CacheConstant;
import org.mat.ipaas.ucenter.biz.common.constant.CommonConstant;
import org.mat.ipaas.ucenter.biz.common.system.vo.LoginUser;
import org.mat.ipaas.ucenter.biz.common.util.RedisUtil;
import org.mat.ipaas.ucenter.biz.common.util.oConvertUtils;
import org.mat.ipaas.ucenter.biz.modules.base.service.BaseCommonService;
import org.mat.ipaas.ucenter.biz.modules.system.service.ISysUserService;
import org.mat.ipaas.ucenter.biz.modules.system.service.impl.SysBaseApiImpl;
import org.mat.ipaas.ucenter.biz.modules.system.vo.SysUserOnlineVO;
import org.mat.ipaas.ucenter.service.api.system.SysUserOnlineRestAPI;
import org.mat.ipaas.ucenter.service.dto.system.vo.SysUserOnlineVODTO;
import org.mat.ipaas.ucenter.service.modules.JwtUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * 在线用户
 * @Author: chenli
 * @Date: 2020-06-07
 * @Version: V1.0
 */
@RestController
@RequestMapping("/sys/online")
@Slf4j
public class SysUserOnlineController implements SysUserOnlineRestAPI {

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    public RedisTemplate redisTemplate;
    @Autowired
    public ISysUserService userService;
    @Autowired
    private SysBaseApiImpl sysBaseApi;

    @Resource
    private BaseCommonService baseCommonService;

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public MatApiResponse<Page<SysUserOnlineVODTO>> list(@RequestParam(name = "username", required = false) String username,
                                                         @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Collection<String> keys = redisTemplate.keys(CommonConstant.PREFIX_USER_TOKEN + "*");
        List<SysUserOnlineVO> onlineList = new ArrayList<SysUserOnlineVO>();
        for (String key : keys) {
            String token = (String) redisUtil.get(key);
            if (StringUtils.isNotEmpty(token)) {
                SysUserOnlineVO online = new SysUserOnlineVO();
                online.setToken(token);
                //TODO 改成一次性查询
                LoginUser loginUser = sysBaseApi.getUserByName(JwtUtils.getUsername(token));
                if (loginUser != null) {
                    //update-begin---author:wangshuai ---date:20220104  for：[JTC-382]在线用户查询无效------------
                    //验证用户名是否与传过来的用户名相同
                    boolean isMatchUsername = true;
                    //判断用户名是否为空，并且当前循环的用户不包含传过来的用户名，那么就设成false
                    if (oConvertUtils.isNotEmpty(username) && !loginUser.getUsername().contains(username)) {
                        isMatchUsername = false;
                    }
                    if (isMatchUsername) {
                        BeanUtils.copyProperties(loginUser, online);
                        onlineList.add(online);
                    }
                    //update-end---author:wangshuai ---date:20220104  for：[JTC-382]在线用户查询无效------------
                }
            }
        }
        Collections.reverse(onlineList);

        Page<SysUserOnlineVO> page = new Page<SysUserOnlineVO>(pageNo, pageSize);
        int count = onlineList.size();
        List<SysUserOnlineVO> pages = new ArrayList<>();
        // 计算当前页第一条数据的下标
        int currId = pageNo > 1 ? (pageNo - 1) * pageSize : 0;
        for (int i = 0; i < pageSize && i < count - currId; i++) {
            pages.add(onlineList.get(currId + i));
        }
        page.setSize(pageSize);
        page.setCurrent(pageNo);
        page.setTotal(count);
        // 计算分页总页数
        page.setPages(count % 10 == 0 ? count / 10 : count / 10 + 1);
        page.setRecords(pages);

        MatApiResponse<Page<SysUserOnlineVODTO>> matApiResponse = new MatApiResponse<>();
        matApiResponse.setSuccess(true);
        matApiResponse.setData(toSysUserOnlineVODTOPage(page));
        return matApiResponse;
    }


    /**
     * 强退用户
     */
    @RequestMapping(value = "/forceLogout", method = RequestMethod.POST)
    public MatApiResponse<Object> forceLogout(@RequestBody SysUserOnlineVODTO sysUserOnlineVODTO) {
        SysUserOnlineVO online = toSysUserOnlineVO(sysUserOnlineVODTO);

        //用户退出逻辑
        if (oConvertUtils.isEmpty(online.getToken())) {
            return MatApiResponse.fail("退出登录失败！");
        }
        String username = JwtUtils.getUsername(online.getToken());
        LoginUser sysUser = sysBaseApi.getUserByName(username);
        if (sysUser != null) {
            baseCommonService.addLog("强制: " + sysUser.getRealname() + "退出成功！", CommonConstant.LOG_TYPE_1, null, sysUser);
            log.info(" 强制  " + sysUser.getRealname() + "退出成功！ ");
            //清空用户登录Token缓存
            redisUtil.del(CommonConstant.PREFIX_USER_TOKEN + online.getToken());
            //清空用户登录Shiro权限缓存
            redisUtil.del(CommonConstant.PREFIX_USER_SHIRO_CACHE + sysUser.getId());
            //清空用户的缓存信息（包括部门信息），例如sys:cache:user::<username>
            redisUtil.del(String.format("%s::%s", CacheConstant.SYS_USERS_CACHE, sysUser.getUsername()));
            //TODO 调用shiro的logout?
            //SecurityUtils.getSubject().logout();
            return MatApiResponse.success("退出登录成功！");
        } else {
            return MatApiResponse.fail("Token无效!");
        }
    }

    private SysUserOnlineVO toSysUserOnlineVO(SysUserOnlineVODTO sysUserOnlineVODTO) {
        if (sysUserOnlineVODTO == null) {
            return null;
        }
        SysUserOnlineVO sysUserOnlineVO = new SysUserOnlineVO();
        sysUserOnlineVO.setId(sysUserOnlineVODTO.getId());
        sysUserOnlineVO.setToken(sysUserOnlineVODTO.getToken());
        sysUserOnlineVO.setUsername(sysUserOnlineVODTO.getUsername());
        sysUserOnlineVO.setRealname(sysUserOnlineVODTO.getRealname());
        sysUserOnlineVO.setAvatar(sysUserOnlineVODTO.getAvatar());
        sysUserOnlineVO.setBirthday(sysUserOnlineVODTO.getBirthday());
        sysUserOnlineVO.setSex(sysUserOnlineVODTO.getSex());
        sysUserOnlineVO.setPhone(sysUserOnlineVODTO.getPhone());
        return sysUserOnlineVO;
    }

    private Page<SysUserOnlineVODTO> toSysUserOnlineVODTOPage(Page<SysUserOnlineVO> page) {
        Page<SysUserOnlineVODTO> sysUserOnlineVODTOPage = new Page<>();
        List<SysUserOnlineVODTO> sysUserOnlineVODTOList = new ArrayList<>();
        if (page != null && CollectionUtils.isNotEmpty(page.getRecords())) {
            for (SysUserOnlineVO online : page.getRecords()) {
                sysUserOnlineVODTOList.add(toSysUserOnlineVODTO(online));
            }
        }

        sysUserOnlineVODTOPage.setTotal(page.getTotal());
        sysUserOnlineVODTOPage.setSize(page.getSize());
        sysUserOnlineVODTOPage.setCurrent(page.getCurrent());
        sysUserOnlineVODTOPage.setRecords(sysUserOnlineVODTOList);
        return sysUserOnlineVODTOPage;
    }

    private SysUserOnlineVODTO toSysUserOnlineVODTO(SysUserOnlineVO online) {
        if (online == null) {
            return null;
        }
        SysUserOnlineVODTO sysUserOnlineVODTO = new SysUserOnlineVODTO();
        sysUserOnlineVODTO.setId(online.getId());
        sysUserOnlineVODTO.setToken(online.getToken());
        sysUserOnlineVODTO.setUsername(online.getUsername());
        sysUserOnlineVODTO.setRealname(online.getRealname());
        sysUserOnlineVODTO.setAvatar(online.getAvatar());
        sysUserOnlineVODTO.setBirthday(online.getBirthday());
        sysUserOnlineVODTO.setSex(online.getSex());
        sysUserOnlineVODTO.setPhone(online.getPhone());
        return sysUserOnlineVODTO;
    }
}
